import cv2


def check_video_stuttering(video_path, threshold=0.1):
    '''
    检测视频是否卡顿或丢帧
    :param video_path:
    :param threshold:
    :return:
    '''
    cap = cv2.VideoCapture(video_path)  # 打开视频文件
    fps = cap.get(cv2.CAP_PROP_FPS)  # 获取视频的帧率
    expected_frame_time = 1 / fps  # 计算每帧的期望时间（秒）

    previous_frame_time = None  # 用于记录前一帧的时间
    dropped_frames = []  # 记录丢帧的时间戳
    stuttering_frames = []  # 记录卡顿帧的时间戳

    frame_count = 0  # 记录帧数

    while True:
        ret, frame = cap.read()  # 读取当前帧
        if not ret:  # 如果帧读取失败，跳出循环
            break

        frame_count += 1  # 增加帧计数
        current_frame_time = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0  # 获取当前帧的时间（秒）

        if previous_frame_time is not None:
            time_diff = current_frame_time - previous_frame_time  # 计算当前帧与前一帧的时间差
            # 检查是否丢帧
            if time_diff > expected_frame_time * 10:  # 如果时间差大于两倍的期望时间，认为丢帧
                dropped_frames.append((frame_count, current_frame_time))  # 记录丢帧的帧数和时间
            # 检查是否卡顿
            if time_diff > expected_frame_time + threshold:  # 如果时间差大于期望时间加上阈值，认为卡顿
                stuttering_frames.append((frame_count, current_frame_time))  # 记录卡顿的帧数和时间
        previous_frame_time = current_frame_time  # 更新前一帧时间
    cap.release()  # 释放视频捕获对象
    return dropped_frames, stuttering_frames  # 返回丢帧和卡顿的信息


if __name__ == '__main__':
    # 使用示例
    video_file_path = '/7M文件大小.mp4'  # 替换为你的视频文件路径
    dropped_frames, stuttering_frames = check_video_stuttering(video_file_path)

    # 输出结果
    if dropped_frames:
        print("丢帧信息:")
        for frame_index, timestamp in dropped_frames:
            print(f"帧索引: {frame_index}, 时间: {timestamp:.2f}秒")
    else:
        print("没有检测到丢帧")

    if stuttering_frames:
        print("卡顿信息:")
        for frame_index, timestamp in stuttering_frames:
            print(f"帧索引: {frame_index}, 时间: {timestamp:.2f}秒")
    else:
        print("没有检测到卡顿帧")
